package com.astar.service.impl;

import com.astar.mapper.MenuMapper;
import com.astar.pojo.Admin;
import com.astar.pojo.Menu;
import com.astar.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author weishen
 * @since 2021-06-21
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    @Resource
    private MenuMapper menuMapper;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public List<Menu> findMenusByAdminId() {
        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
        Integer adminId = ((Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId();
        List<Menu>  menus = (List<Menu>) ops.get("menu_" + adminId);
        if(CollectionUtils.isEmpty(menus)){
            //从数据库中查询
            menus = menuMapper.findMenusByAdminId(adminId);
            ops.set("menu_" + adminId,menus);
            System.out.println("从数据库获取...");
        }else{
            System.out.println("从缓存中获取...");
        }
        return menus;
    }


}
